﻿using AutoMapper;
using B.S.Packaged.Domain;
using B.S.Packaged.ErrorCode;
using B.S.Packaged.WebAPI.Read.Application.Command.MonitorCommand;
using B.S.Packaged.WebAPI.Read.Dtos;
using MediatR;
using SqlSugar;

namespace B.S.Packaged.WebAPI.Read.Application.CommandHander.MonitorCommandHander
{
    public class QueryMonitorCommandHander : IRequestHandler<QueryMonitoryCommand, APIPaging<List<MonitorDtos>>>
    {
        private readonly IMapper mapper;
        private readonly ISqlSugarClient db;

        public QueryMonitorCommandHander(IMapper mapper, ISqlSugarClient db)
        {
            this.mapper = mapper;
            this.db = db;
        }

        public Task<APIPaging<List<MonitorDtos>>> Handle(QueryMonitoryCommand request, CancellationToken cancellationToken)
        {
            APIPaging<List<MonitorDtos>> result = new APIPaging<List<MonitorDtos>>();

            var item = db.Queryable<MonitorModel>()
                       .InnerJoin<Equipment_Information>((a, b) => a.Id == b.Id)
                       .Where((a, b) => a.Del == false)
                       .Select((a, b) => new MonitorDtos
                       {
                           MonitorId = a.MonitorId,
                           ProductName = a.ProductName,
                           Brand = a.Brand,
                           MaterialName = a.MaterialName,
                           PackingSpecifications = a.PackingSpecifications,
                           PackingDate = a.PackingDate,
                           PackingPlan = a.PackingPlan,
                           Packers = a.Packers,
                           QualityInspectors = a.QualityInspectors,
                           Id = b.Id,
                           TestResults = a.TestResults,
                           InkjetEffect = a.InkjetEffect,
                           Tightness = a.Tightness,
                           Compliance = a.Compliance,
                           abnormal = a.abnormal,
                           Reviewers = a.Reviewers,
                           AuditDate = a.AuditDate,
                           Del = a.Del,

                           Equipment_Name = b.Equipment_Name,
                           Model = b.Model,
                           Manufacturer = b.Manufacturer,
                           Purchase_Date = b.Purchase_Date,
                           Status = b.Status,
                       });

            result.TotalCount = item.Count();
            result.TotalPage = (int)Math.Ceiling(result.TotalCount * 1.0 / request.PageSize);
            item = item.OrderByDescending(a => a.MonitorId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);

            result.code = APIResultCode.success;
            result.msg = "查询成功";
            result.data = mapper.Map<List<MonitorDtos>>(item.ToList());

            return Task.FromResult(result);
        }
    }
}
